#encoding:utf-8

from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import HelperDriver
import os.path
import urllib
import time
import logging
import threading
import traceback
import Const

logging.config.fileConfig(Const.logCfgPath)
logger = logging.getLogger("example01")

def loginCatetory(url):

       driver = HelperDriver.getRowDriver()
       try:
                logger.info('begin get url %s' % url)
                driver.get(url)
                pageOK = isNormal(driver)
                if not pageOK:
                    return None
                wdw = WebDriverWait(driver, Const.req_timeout)
       except TimeoutException,te:
                  logger.error( 'loginCatetory %s time out !!!' % url)
                  driver.save_screenshot(Const.pngDir+'home_timeout.png')
                  return None
       return driver



def getPageNum(url):
     #/hot/page/150?s=4729364
    pageStartIndex =  url.rfind('/')
    pageEndIndex =  url.find('?')
    pageNum = url[pageStartIndex+1:pageEndIndex]
    return pageNum

#get url template
pageObj='##'
def getPatternURL(url):
    page= getPageNum(url)
    url = url.replace(page,pageObj,2)  #replace 1 time
    return url

#assemble url
def getUrlWithPageNum(urlPattern,newPageNum):
    url = urlPattern.replace(pageObj,newPageNum)
    return url




def isNormal(driver,errMsg=const.ErrorMsg):
    str = driver.page_source
    index1 = str.find(errMsg)
    if index1 == -1:   # not find error msg
        return True
    return False

def initGatherTarget():
    target =[]

    return target


def progressCallback(a,b,c):

    per = 100.0 * a * b / c
    if per > 100:
        per = 100
    print '%.2f%%' % per

def getImageName(url): 
   index =  url.rfind('/')
   imageName = url[index+1:len(url)]
   return imageName

def downloadPic(url,local):
    name = getImageName(url)
    fName = Const.originImgsDir + name
    urllib.urlretrieve(url, fName, progressCallback)

def initDirs(paths):
    for p in paths:
       if not os.path.exists(p):
          os.makedirs(p)


def initEnv():
     dirs=[Const.pngDir,Const.accountDir,Const.cookiesDir,Const.originPagesDir,Const.originImgsDir]
     initDirs(dirs)

def getNetWorkSpeed():
    import urllib
    speed = 0.0
    try:
        start = time.time()
        resp = urllib.urlopen(Const.URL_HOME)
        respCode = resp.getcode()
        respURL = resp.geturl()
        respInfo = resp.info()
        end = time.time()
        speed = end - start

        return True,speed
    except Exception,e:
         return False,0.0


def isSuccessLogin(driver):
   isLogin =  HelperDriver.isWebElementExist(driver,'//div[@class="userbar"]')
   return isLogin


def isExistFrame(driver):
    return HelperDriver.isWebElementExist(driver,'//iframe')

def runTestNetSpeed():
        testStart = time.time()
        ok = 0
        fail = 0
        i=0
        cost_time = 0.0
        while i < int(Const.network_chk_num):
            isLoginOk,speed  =  getNetWorkSpeed()
            if isLoginOk:
               #logger.info('open url [%s] costs [%f] seconds' % (isLoginOk,speed))
               cost_time = cost_time + speed
               ok = ok+1
            else:
               fail =fail+1
               logger.error('runTestNetSpeed login failed!')
            i=i+1
        testEnd = time.time()
        if ok >0:
           eachLoginCostSec = round (   cost_time/ok , 2)
           logger.info('visit url costs [%f] seconds' % eachLoginCostSec)
        else:
            eachLoginCostSec=999999.00
            logger.error('runTestNetSpeed all login failed')
        return eachLoginCostSec

def isGatherAccordingDB():
    return True

def isGatherAccordingNetSpeed():
    avgSpeed = runTestNetSpeed()
    if avgSpeed < const.network_bad:
        return True
    else:
        logger.warning('network was worse %f' % avgSpeed)
        return False

env_network=False
env_db=False

def envMonitor():
    global env_network
    global env_db
    while True:
       env_network = isGatherAccordingNetSpeed()
       env_db  =  isGatherAccordingDB()
       time.sleep(Const.network_chk_period)




if __name__=='__main__':
     initEnv()
     monitorThread = threading.Thread(target=envMonitor)
     monitorThread.setDaemon(True)
     monitorThread.start()

     while(True):
          if env_network and  env_db:
              gather()
          else:
              logger.error('env failed need sleep %d' % Const.env_failed_sleep)
              time.sleep(Const.env_failed_sleep)
